<?php
namespace Common\Model;

class RedeemModel extends \Think\Model
{
	//自动验证
	protected $_validate = array(
			//新增
			array('user_id', '/^[1-9]\d*$/', '请传入用户ID', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
			array('invest_id', '/^[1-9]\d*$/', '请传入投资ID', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
			array('count', '/^[1-9]\d*$/', '请传入赎回份数', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
	);
	
	//自动完成
	protected $_auto = array(
			array('create_time', NOW_TIME, self::MODEL_INSERT, 'string'),
			array('update_time', NOW_TIME, self::MODEL_BOTH, 'string'),
			array('status', 0, self::MODEL_INSERT, 'string'),
	);
	
	/**
	 * 添加赎回记录
	 * @param array $data
	 */
	public function addRedeem($data)
	{
		//创建数据对象
		if(!$this->create($data)) return array('error' => 1, 'info' => $this->getError());
		$investId = $this->invest_id;
		$count = $this->count;
		$userId = $this->user_id;
		
		//查询投资记录
		$invest = M('Invest')->where(array('id' => $investId,'user_id'=>$userId))->find();
		if(!$invest) return array('error' => 1, 'info' => '投资信息查询失败');
		if($invest['status'] === '2') {
			return array('error' => 1, 'info' => '该定单未支付，无法赎回');
		} else if($invest['status'] === '4') {
			return array('error' => 1, 'info' => '该定单已经赎回');
		} else if($invest['status'] <= 0) {
			return array('error' => 1, 'info' => '该定单无效');
		}
		
		//查询该投资记录的赎回记录
		$redeemList = $this->where(array('invest_id'=>$investId,'status'=>array('egt',0)))->select();
		if($redeemList === false) return array('error' => 1, 'info' => '投资信息查询失败');
		if(!$redeemList) $redeemList = array();
		
		// 查询可赎回数量
		$redeemCount = 0;
		foreach($redeemList as $rl) {
			$redeemCount = bcadd($redeemCount,$rl['count']);
		}
		$leftCount = bcsub($invest['count'], $redeemCount);
		if($leftCount < $count) return array('error' => 1, 'info' => '赎回份数超过剩余份数');
		
		//查询基金信息
		$fund = M('Fund')->where(array('id' => $invest['fund_id'], 'status' => 1))->find();
		if(!$fund) return array('error' => 1, 'info' => '基金信息查询失败');
		
		// 开放期赎回
		$where = array('fund_id'=>$invest['fund_id'],'status'=>1);
		if(NOW_TIME >=  $fund['open_start_time'] && NOW_TIME <= $fund['open_end_time']) {
			$defaultsRate = 0;
			
			//如果是在开放期下单成功，但在开放期结束之前就赎回则属于违约,没有利息
			//$etime =  strtotime('1 day', $invest['effective_time']);
			if($invest['effective_time'] > $fund['open_start_time']) {
				$defaultsRate = global_config('break_contract_rate');
				if($defaultsRate !== '0' && $defaultsRate !== 0 && !$defaultsRate) return array('error' => 1, 'info' => '配置项查询失败');
				$endNetvalue = $invest['netvalue'];
				$broken = 1;
				
			// 回款之后赎回，不违约
			} else {
				$where['netvalue_time'] = array('elt', $fund['open_start_time']);
				$endNetvalue = M('FundNetvalue')->where($where)->order('netvalue_time desc')->find();
				if(!$endNetvalue) return array('error' => 1, 'info' => '净值获取失败1');
				$endNetvalue = $endNetvalue['value'];
				$broken = 0;
			}
		
		// 非开放期赎回，属于违约
		} else {
			$defaultsRate = global_config('break_contract_rate');
			if($defaultsRate !== '0' && $defaultsRate !== 0 && !$defaultsRate) return array('error' => 1, 'info' => '配置项查询失败');
			$where['netvalue_date'] = array('lt', date('Y-m-d', NOW_TIME));
			$endNetvalue = M('FundNetvalue')->where(array('fund_id'=>$invest['fund_id'],'status'=>1))->order('netvalue_time desc')->find();
			if(!$endNetvalue) return array('error' => 1, 'info' => '净值获取失败2');
			$endNetvalue = $endNetvalue['value'];
			$broken = 1;
		}
		
		$this->broken = $broken;
		//赎回总金额
		$total = bcmul($count, $endNetvalue, 4);
		
		//违约金
		$defaultMoney = bcmul($total, $defaultsRate, 4);
		$this->broken_money = $defaultMoney;
		
		//扣除违约金之后的赎回总金额
		$total = bcsub($total, $defaultMoney, 2);
		$this->amount = $total;
		
		//TODO:推荐人奖励
		$param['userId'] = $data['user_id']; //用户id
		$param['income'] = ''; //公司收益
		\Think\Hook::listen('task_recommend', $param);

		//添加赎回记录
		$id = $this->add();
		if(!$id) return array('error' => 1, 'info' => '赎回失败');
		
		// 构造返回数据
		$redeem['total'] = $total;
		$redeem['id'] = $id;
		$redeem['invest_id'] = $investId;
		$redeem['broken_money'] = $defaultMoney;
		$redeem['broken'] = $broken;
		
		return array('error' => 0, 'info' => $this->find($redeem));
	}
	
	/**
	 * 查询赎回记录
	 */
	public function searchRedeem($where = false, $option = false, $order='', $field=true)
	{
		if($option ) {
			if($option['page'] && $option['size']) {
				$page = $option['page'];
				$size = $option['size'];
				$this->page($page, $size);
			}
				
			//分组
			if($option['group']) $this->group($option['group']);
				
			//查询多少条记录
			if($option['limit']) $this->limit($option['limit']);
		}
	
		if($where) $this->where($where);
		$list = $this->order($order)->field($field)->select();
		return $list;
	}
	
	/**
	 * 查询赎回详情
	 * @param int|string $investId
	 * @param int|string $userId
	 */
	public function redeemDetail($investId, $userId)
	{
		//查询投资记录
		$field = 'id,order_no,user_id,fund_id,fund_name,amount,count,contract_id,contract_name,end_time,effective_time,type,status';
		$invest = M('Invest')->where(array('id'=>$investId,'user_id'=>$userId,'status'=>array('gt',0)))->field($field)->find();
		if(!$invest) return array('error'=>1,'info'=>'投资记录查询失败');
		
		//查询赎回记录
		$redeemList = M('Redeem')->where(array('invest_id'=>$investId,'user_id'=>$userId,'status'=>array('egt',0)))->select();
		if($redeemList === false) return array('error'=>1,'info'=>'赎回记录查询失败');
		if(!$redeemList) $redeemList = array();
		
		//计算还可以赎回多少份
		$count = 0;
		foreach($redeemList as $rl) {
			$count = bcadd($rl['count'], $count);
		}
		$leftCount = $invest['count'] - $count;
		$invest['left_count'] = $leftCount;
		$invest['redeem'] = $redeemList;
		
		return array('error'=>0, 'info'=>$invest);
	}
}